<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单编号" prop="ordersNumber">
        <el-autocomplete
          v-model="queryParams.ordersNumber"
          :fetch-suggestions="querySearchAsync"
          placeholder="请输入设备编号"
          clearable
        ></el-autocomplete>
      </el-form-item>
      <el-form-item label="支付时间">
        <el-date-picker
          v-model="dateRangePay"
          style="width: 240px"
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="支付方式" prop="paymentMethod">
        <el-select
          v-model="queryParams.paymentMethod"
          placeholder="支付方式"
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="item in dict.type.payment_method"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="chargeRecordsList" @selection-change="handleSelectionChange">
      <el-table-column label="订单编号" align="center" prop="ordersNumber" />
      <el-table-column label="用户" align="center" prop="nickName" />
      <el-table-column label="支付方式" align="center" prop="paymentMethod">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.payment_method" :value="scope.row.paymentMethod"/>
        </template>
      </el-table-column>
      <el-table-column label="支付时间" align="center" prop="createdTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdTime) }}</span>
        </template>
        </el-table-column>
      <el-table-column label="支付金额" align="center" prop="paymentAmount"></el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <div style="display: flex; justify-content: space-around">
          <el-button size="mini" @click="handlePile()">选择充电桩</el-button>
          <span style="width: 200px; line-height: 30px;">充电桩编号:<span style="margin-left: 10px"></span>{{ chargePile.number }}</span>
          <span style="width: 200px; line-height: 30px;">充电桩功率:<span style="margin-left: 10px"></span>{{ chargePile.power }} <span v-if="chargePile.power">kW</span> </span>
          <span style="width: 200px; line-height: 30px;">
              充电桩类型:<span style="margin-left: 10px"></span><dict-tag style="display: inline-block" :options="dict.type.charge_type" :value="chargePile.types"/>
            </span>
        </div>

        <hr>

        <el-row :gutter="24" class="mb8">
          <el-col :span="12">
            <el-form-item label="充电时间" prop="chargeTime">
              <el-input-number :disabled="disabled" v-model="form.chargeTime" :precision="2"></el-input-number>
              <span style="margin-left: 10px">小时</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="充电量" prop="chargeAmount">
              <el-input-number :disabled="disabled" v-model="form.chargeAmount" :precision="2"></el-input-number>
              <span style="margin-left: 10px">度</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="24" class="mb8">
          <el-col :span="12">
            <el-form-item label="充电金额" prop="paymentAmount">
              <el-input-number :disabled="disabled" @change="changeVal" v-model="form.paymentAmount" :step="5" :min="0" :precision="2"></el-input-number>
              <span style="margin-left: 10px">元</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="使用积分余额" prop="pointBalance">
              <el-input-number :disabled="disabled" @change="changeVal" v-model="form.pointBalance" :step="10" :min="0" :max="Number(this.points.pointBalance)" :precision="2"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>

        <div style="display: flex; justify-content: right">
          <span>应付金额:<span style="margin-left: 10px"></span>{{ (form.paymentAmount - (form.pointBalance / 1000)).toFixed(2) }}</span>
          <span style="margin-left: 10px">元</span>
        </div>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :disabled="disabled" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 选择充电桩对话框 -->
    <el-dialog title="选择充电桩" :visible.sync="openPile" width="800px" append-to-body>
      <div>
        <el-form :model="queryPileParams" ref="queryPileForm" size="small" :inline="true" v-show="showPileSearch" label-width="68px">
          <el-form-item label="设备类型" prop="types">
            <el-select
              v-model="queryPileParams.types"
              placeholder="设备类型"
              clearable @clear="handlePileQuery"
              @change="handlePileQuery"
              style="width: 240px"
            >
              <el-option
                v-for="dict in dict.type.charge_type"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="设备编号" prop="number">
            <el-input
              v-model="queryPileParams.number"
              placeholder="请输入设备编号"
              clearable
              @keyup.enter.native="handlePileQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handlePileQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetPileQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <right-toolbar :showSearch.sync="showPileSearch" @queryTable="getPileList"></right-toolbar>
        </el-row>

        <el-table v-loading="loadingPile" :data="chargePileList" @selection-change="handleSelectionChange">
          <el-table-column label="设备编号" align="center" prop="number" />
          <el-table-column label="设备类型" align="center" prop="types">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.charge_type" :value="scope.row.types"/>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-info"
                @click="selectPile(scope.row)"
              >选择</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-info"
                @click="handleRepair(scope.row)"
              >报修</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="totalPile>0"
          :total="totalPile"
          :page.sync="queryPileParams.pageNum"
          :limit.sync="queryPileParams.pageSize"
          @pagination="getPileList"
        />
      </div>
      <div slot="footer" class="dialog-footer">
        <span></span>
        <el-button @click="cancelPile">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 报修对话框 -->
    <el-dialog title="报修" :visible.sync="openRepair" width="800px" append-to-body>
      <el-form ref="form" :model="formRepair" :rules="rulesRepair" label-width="100px">
        <el-form-item label="报修原因" prop="requestContent">
          <el-input :disabled="disabled" type="textarea" v-model="formRepair.requestContent" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :disabled="disabled" type="primary" @click="submitFormRepair">确 定</el-button>
        <el-button @click="cancelRepair">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listChargePile,
    getChargePile,
  } from "@/api/chargepile/chargePileManage";
  import {
    listChargeRecordsVo,
    addChargeRecords,
  } from "@/api/chargepile/chargeRecords";
  import {
    addRepairRecord,
  } from "@/api/chargepile/repairRecord";
  import {
    getUserChargeConfig,
  } from "@/api/chargepile/chargeConfig";
  import {
    getPoints
  } from "@/api/chargepile/points";
  import {
    listOrderNumber
  } from "@/api/chargepile/orders";

  export default {
    name: "Orders",
    dicts: ['charge_type', 'charge_status', 'price', 'payment_method'],
    data() {
      return {
        // 用户充电桩配置
        chargeConfig:{},
        points:{},
        // 遮罩层
        loading: true,
        // 充电桩遮罩层
        loadingPile: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 显示充电桩搜索条件
        showPileSearch: true,
        // 总条数
        total: 0,
        totalPile: 0,
        // 表格数据
        chargeRecordsList: [],
        // 充电桩表格数据
        chargePileList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 是否选择充电桩弹出层
        openPile: false,
        openRepair: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          beginTime: null,
          endTime: null,
        },
        // 充电桩查询参数
        queryPileParams:{
          pageNum: 1,
          pageSize: 10,
          beginTime: null,
          endTime: null,
        },
        queryNumber: [],
        // 日期范围
        dateRangePay: [],
        // 表单参数
        form: {
          chargeTime: undefined,
          chargeAmount: undefined,
          paymentAmount: undefined,
          pointBalance: undefined,
          payment: undefined,
        },
        formRepair: {},
        // 充电桩
        chargePile:{
          chargePileId: undefined,
          number: undefined,
          types: undefined,
          power: undefined,
        },
        // 表单禁用
        disabled: false,
        // 表单校验
        rules: {

        },
        rulesRepair:{
          requestContent: [
            { required: true, message: "报修原因不能为空", trigger: "blur" }
          ],
        },
      };
    },
    watch: {
      'form.chargeTime': {
        handler(newVal, oldVal) {
          if (newVal && this.chargePile.number !== undefined) {
            this.form.chargeAmount = this.chargePile.power * this.form.chargeTime;
            if(this.chargePile.types === "0"){
              this.form.paymentAmount = this.form.chargeTime * this.dict.type.price[0].value;
            }
            if(this.chargePile.types === "1"){
              this.form.paymentAmount = this.form.chargeTime * this.dict.type.price[1].value;
            }
          }
        },
        immediate: false,
        deep: true,
      },
      'form.chargeAmount': {
        handler(newVal, oldVal) {
          if (newVal && this.chargePile.number !== undefined) {
            this.form.chargeTime = this.form.chargeAmount / this.chargePile.power;
          }
        },
        immediate: false,
        deep: true,
      },
      'form.paymentAmount': {
        handler(newVal, oldVal) {
          if (newVal && this.chargePile.number !== undefined) {
            if(this.chargePile.types === "0"){
              this.form.chargeTime = this.form.paymentAmount / this.dict.type.price[0].value;
            }
            if(this.chargePile.types === "1"){
              this.form.chargeTime = this.form.paymentAmount / this.dict.type.price[1].value;
            }
          }
        },
        immediate: false,
        deep: true,
      }
    },
    created() {
      this.getList();
      this.getUserChargeConfig();
      this.getPoints();
      this.listOrderNumber();
    },
    methods: {
      // 设备编号查询自动补全
      querySearchAsync(queryString, cb) {
        var number = this.queryNumber;
        var results = queryString ? number.filter(this.createStateFilter(queryString)) : number;

        clearTimeout(this.timeout);
        this.timeout = setTimeout(() => {
          cb(results);
        }, 3000 * Math.random());
      },
      createStateFilter(queryString) {
        return (state) => {
          return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
        };
      },
      listOrderNumber(){
        listOrderNumber().then(response => {
          this.queryNumber = response.data;
        });
      },
      //解决点击计数器失效问题
      changeVal(){
        this.$forceUpdate();
      },
      // 获取充电桩配置
      getUserChargeConfig(){
        getUserChargeConfig().then(response => {
          this.chargeConfig = response.data;
        });
      },
      // 获取积分
      getPoints(){
        getPoints().then(response => {
          this.points = response.data;
          this.points.pointBalance = String(this.points.pointBalance);
        });
      },
      /** 查询列表 */
      getList() {
        this.loading = true;
        if(this.dateRangePay !== null){
          this.queryParams.beginTimePay = this.dateRangePay[0]
          this.queryParams.endTimePay = this.dateRangePay[1]
        }else{
          this.queryParams.beginTimePay = null;
          this.queryParams.endTimePay = null;
        }
        listChargeRecordsVo(this.queryParams).then(response => {
          this.chargeRecordsList = response.data.list;
          this.total = response.data.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
        this.disabled = false;
      },
      // 取消充电桩按钮
      cancelPile() {
        this.openPile = false;
      },
      // 取消按钮
      cancelRepair() {
        this.openRepair = false;
        this.formRepair.requestContent = "";
      },
      // 表单重置
      reset() {
        this.chargePile = {
          number:undefined,
          power: undefined,
          types: undefined,
        },
          this.form = {
            chargeTime: undefined,
            chargeAmount: undefined,
            paymentAmount: undefined,
            pointBalance: undefined,
          };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 搜索按钮操作 */
      handlePileQuery() {
        this.queryPileParams.pageNum = 1;
        this.getPileList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.dateRangePay = []
        this.resetForm("queryForm");
        this.handleQuery();
      },
      /** 重置按钮操作 */
      resetPileQuery() {
        this.resetForm("queryPileForm");
        this.handlePileQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.postId)
        this.single = selection.length!=1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.disabled = false;
        this.reset();
        this.open = true;
        this.title = "新增充电记录";
        this.form.paymentAmount = this.chargeConfig.chargeAmount;
        this.form.pointBalance = 0;
        this.initAMap()
      },
      /** 查看按钮操作 */
      handleInfo(row){
        this.handleUpdate(row)
        this.title = "查看充电记录";
        this.disabled = true;
        // this.initAMap()
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.disabled = false;
        this.reset();
        const chargePileId = row.id || this.ids
        getChargePile(chargePileId).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改设备";
          this.initAMap()
        });
      },
      /** 弹出充电桩弹窗按钮操作 */
      handlePile() {
        this.openPile = true;
        this.loadingPile = true;
        this.queryPileParams.types = this.chargeConfig.chargePileType;
        this.queryPileParams.status = "0";
        listChargePile(this.queryPileParams).then(response => {
          this.chargePileList = response.data.list;
          this.totalPile = response.data.total;
          this.loadingPile = false;
        });
      },
      /** 查询充电桩列表 */
      getPileList() {
        this.loadingPile = true;
        listChargePile(this.queryPileParams).then(response => {
          this.chargePileList = response.data.list;
          this.total = response.data.total;
          this.loadingPile = false;
        });
      },
      /** 选择当前充电桩 */
      selectPile(row){
        this.chargePile.chargePileId = row.id;
        this.chargePile.number = row.number;
        this.chargePile.types = row.types;
        this.chargePile.power = row.power;
        if(this.chargePile.types === "0"){
          this.form.chargeTime = this.form.paymentAmount / this.dict.type.price[0].value;
        }
        if(this.chargePile.types === "1"){
          this.form.chargeTime = this.form.paymentAmount / this.dict.type.price[1].value;
        }
        this.form.chargePileId = row.id
        this.openPile = false;
      },
      /** 选择当前充电桩 */
      handleRepair(row){
        this.openRepair = true;
        this.formRepair.chargePileId = row.id;
        this.formRepair.requestStatus = "0";
      },
      /** 提交按钮 */
      submitForm: function() {
        if (this.chargePile.number){
          this.form.payment = (this.form.paymentAmount - (this.form.pointBalance / 1000)).toFixed(2);
          this.$refs["form"].validate(valid => {
            if (valid) {
              addChargeRecords(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          });
        }else{
          this.$message.error("请选择充电桩");
        }
      },
      /** 提交按钮 */
      submitFormRepair: function() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            addRepairRecord(this.formRepair).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.openRepair = false;
              this.getPileList();
            });
          }
        });
      },
    }
  };
</script>
